import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-11-10
 * Time: 13:43
 */
public class MyThreadPool {
    public BlockingQueue<Runnable> queue = null;

     //初始化线程池，创建固定个数的线程
    // 这里使用ArrayBlockingQueue作为任务队列, 容量为1000

    public MyThreadPool(int n){
        queue = new ArrayBlockingQueue<>(1000);


        // 创建 N 个线程
        for (int i = 0; i < n; i++) {

            Thread t1 = new Thread(() -> {

                while (true) {
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            t1.start();
        }
    }

    private void submit(Runnable task){
        task.run();
    }

    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(10);//10个线程
        // 向线程池提交100个任务
        for (int i = 0; i < 100; i++) {

            int id = i;
            myThreadPool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " " + "id " + id);
            });
        }
    }
}
